package cn.stylefeng.guns.modular.cb.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.auth.service.AuthService;
import cn.stylefeng.guns.base.consts.ConstantsContext;
import cn.stylefeng.guns.modular.cb.entity.CbWxInfo;
import cn.stylefeng.guns.modular.cb.service.*;
import cn.stylefeng.guns.modular.cb.service.impl.WxService;
import cn.stylefeng.guns.modular.cb.util.SMSUtil;
import cn.stylefeng.guns.sys.core.exception.InvalidKaptchaException;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.UserDto;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import cn.stylefeng.roses.kernel.model.response.SuccessResponseData;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 客户登录管理
 */
@RestController
@RequestMapping("/api/customer")
@Validated
public class CustomerLoginController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(CustomerLoginController.class);

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Value("${login.pwd}")
    private String pwd;

    @Autowired
    private CustomerLoginService customerLoginService;

    @Autowired
    private AuthService authService;

    @Autowired
    private WxService wxService;

    @Autowired
    private UserService userService;

    /**
     * 获取微信openId
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping("/wx_openId")
    public ResponseData wxOpenId(String code){
        JSONObject data = this.customerLoginService.saveWxOpenId(code);
        String openid = data.getString("openid");
        //前端只需要openid
        JSONObject openJSON = new JSONObject();
        openJSON.put("openid", openid);
        logger.info("data: {}", data);
        return ResponseData.success(openJSON);
    }

    /**
     * 通过openId获取用户
     * @param openid
     * @return
     */
    @RequestMapping(value = "/user_openId", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData loginByOpenId(String openid){
        User user = customerLoginService.getUserByOpenId(openid);
        return ResponseData.success(user);
    }

    /**
     * 发送验证码
     * @return
     */
    @RequestMapping("/send_yzm")
    public ResponseData sendYZM(String phone){
        SMSUtil.sendSMSByYZM(phone);
        return ResponseData.success();
    }

    /**
     * 微信注册/登录
     */
    @RequestMapping("/wx_register")
    public ResponseData wxRegister(CbWxInfo cbWxInfo){
        //解析微信电话号码
        String phone = "";
        try{

            phone = wxService.getPhone(cbWxInfo);
            User theUser = userService.getByAccount(phone);
            if (theUser==null){
                logger.info("用户不存在, 进行注册");
                //注册
                UserDto user = new UserDto();
                user.setAccount(phone);
                user.setPassword(pwd);
                user.setOpenId(cbWxInfo.getOpenid());
                user.setReferees(cbWxInfo.getReferees());
                customerLoginService.addUser(user);
            }
        }catch (Exception e){
            logger.error("wxRegister error: ", e);
        }

        //登录并创建token
        String token = authService.login(phone, pwd);
        return new SuccessResponseData(token);
    }

    /**
     * 手机号/验证码注册用户
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping("/register")
    public ResponseData add( UserDto userInfo, String yzm) {
        try{
            //短信验证码 验证通过后进行注册
            String smsCode = SMSUtil.getCode(userInfo.getAccount());
            if (StringUtils.isEmpty(smsCode) || !smsCode.equals(yzm)){//验证码为空或不相等
                return ResponseData.error("验证码错误");
            } else {
                SMSUtil.remove(userInfo.getAccount());
            }

            User theUser = userService.getByAccount(userInfo.getAccount());
            if (theUser==null){
                logger.info("用户不存在, 进行注册");
                //注册
//            userInfo.setPassword(pwd);
//            customerLoginService.addUser(userInfo);

                UserDto user = new UserDto();
                user.setAccount(userInfo.getAccount());
                user.setPassword(pwd);
                user.setOpenId(userInfo.getOpenId());
                user.setReferees(userInfo.getReferees());
                customerLoginService.addUser(user);
            }
        }catch (Exception e){
            logger.error("register add error: ", e);
        }

        //登录并创建token
        String token = authService.login(userInfo.getAccount(), pwd);

        return new SuccessResponseData(token);
    }

    /**
     * 点击登录执行的动作
     * 用户名时，启用验证码验证的方式登录
     * 有openId时，通过openId获取用户信息进行登录
     * @author fengshuonan
     * @Date 2018/12/23 5:42 PM
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData loginVali(HttpServletRequest request, HttpServletResponse response) {
        String username = super.getPara("username");
        String password = "123qwe";
        String yzm = super.getPara("yzm");
        String openId = super.getPara("openid");

        if (StringUtils.isEmpty(username)){
            //微信openId登录
            User user = customerLoginService.getUserByOpenId(openId);
            if (user==null || StringUtils.isEmpty(user.getAccount())){
                throw new RequestEmptyException("用户不存在！");
            }
            username = user.getAccount();
        }else {
            //短信验证吗
            String smsCode = SMSUtil.getCode(username);
            if (StringUtils.isEmpty(smsCode) || !smsCode.equals(yzm)) {//验证码不相等
                throw new RequestEmptyException("验证码错误！");
            } else {
                SMSUtil.remove(username);
            }
        }

        if (ToolUtil.isOneEmpty(username, password)) {
            throw new RequestEmptyException("账号或密码为空！");
        }

        //验证验证码是否正确
        if (ConstantsContext.getKaptchaOpen()) {
            String kaptcha = super.getPara("kaptcha").trim();
            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
                throw new InvalidKaptchaException();
            }
        }

        //登录并创建token
        String token = authService.login(username, password);
        return new SuccessResponseData(token);
    }

    /**
     * 获取登录用户
     * @return
     */
    @RequestMapping("/get_login_user")
    @ResponseBody
    public ResponseData getLoginUser(){
        LoginUser user = LoginContextHolder.getContext().getUser();
        return ResponseData.success(user);
    }

    /**
     * 设置手机号
     * @param userId
     * @param account
     * @return
     */
    @RequestMapping("/set_account")
    @ResponseBody
    public ResponseData setAccount(Long userId, String account){
        Integer result = customerLoginService.setAccount(userId, account);
        return ResponseData.success(result);
    }

    /**
     * 删除用户
     * @return
     */
    @RequestMapping("/delete_account")
    @ResponseBody
    public ResponseData deleteAccount(){
        customerLoginService.deleteUser();
        return ResponseData.success();
    }

    /**
     * 设置手机号
     * @return
     */
    @RequestMapping("/set_phone")
    @ResponseBody
    public ResponseData setPhone(Long id, String phone, String yzm){
//        LoginUser user = LoginContextHolder.getContext().getUser();
        //短信验证码 验证通过后进行注册
        String smsCode = SMSUtil.getCode(phone);
        if (StringUtils.isEmpty(smsCode) && smsCode.equals(yzm)){//验证码为空或不相等
            return ResponseData.error(Integer.valueOf(smsCode), "验证码错误");
        } else {
            SMSUtil.remove(phone);
        }
        return ResponseData.success();
    }

    /**
     * 设置用户关注公众号状态
     * @return
     */
    @RequestMapping("/set_focus")
    @ResponseBody
    public ResponseData setFocus(Long userId, Boolean focus){
        userService.setFocus(userId, focus);
        return ResponseData.success();
    }
}